package com.lagou.educourseboot.service.impl;

import com.lagou.eduapi.entity.Course;
import com.lagou.educourseboot.mapper.CourseMapper;
import com.lagou.educourseboot.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@Service
public class CourseServiceImpl implements CourseService {

    @Autowired
    private CourseMapper courseMapper;

    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;
    @Override
    public List<Course> getAllCourse() {
        //1.去redis查询数据集合
        System.out.println("+++++查询redis++++");
        List<Course> list = (List<Course>) redisTemplate.opsForValue().get("allCourses");
        //2.如果redis中没有的话，去查数据库
        if (list == null) {
            //第一个人走流程 先去redis找，如果是空再去mysql找
            synchronized (this) {
                list = (List<Course>) redisTemplate.opsForValue().get("allCourses");
                if (list == null) {
                    System.out.println("+++查询MySQL++++");
                    list = courseMapper.getAllCourse();
                    //3.将数据集合放入redis
                    redisTemplate.opsForValue().set("allCourses", list, 10, TimeUnit.SECONDS);
                }
            }
        }
        return list;
    }

    @Override
    public List<Course> getMyCoursesById(List<String> idList) {
        return courseMapper.getMyCoursesById(idList);
    }

    @Override
    public Course getCourseById(String courseId) {
        return courseMapper.getCourseById(courseId);
    }
}
